package com.bite.friend.service.user.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.security.handler.ServiceException;
import com.bit.common.security.service.TokenService;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.enums.ExamListType;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.friend.aspect.CheckUserStatus;
import com.bite.friend.domain.exam.Exam;
import com.bite.friend.domain.exam.dto.ExamQueryDTO;
import com.bite.friend.domain.exam.vo.ExamVO;
import com.bite.friend.domain.user.UserExam;
import com.bite.friend.manager.ExamCacheManager;
import com.bite.friend.manager.UserCacheManager;
import com.bite.friend.mapper.exam.ExamMapper;
import com.bite.friend.mapper.user.UserExamMapper;
import com.bite.friend.service.user.IUserExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserCacheManager userCacheManager;

    @Value("${jwt.secret}")
    private String secret;


    /**
     * 竞赛报名
     * @param token
     * @param examId
     * @return
     */
    @CheckUserStatus
    @Override
    public int enter(String token, Long examId) {
//        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
//        //获取当前用户的信息
//        UserVO user = userCacheManager.getUserById(userId);
//        //根据status判断
//        if (user.getStatus() == 0){
//            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
//        }

        Exam exam = examMapper.selectById(examId);
        //竞赛不存在
        if (exam == null){
            throw new ServiceException(ResultCode.EXAM_NOT_EXIST);
        }
        //竞赛已经开始
        if (exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        //从token中获取userId
//        Long userId = tokenService.getUserId(token,secret);

        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //是否已经报名 报名不能再次报名
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if (userExam != null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        //在缓存中存储
        examCacheManager.addUserExamCache(userId,examId);
        //在数据库存储信息
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }


    /**
     * 我的竞赛
     * @param examQueryDTO
     * 思路,先从缓存中查询,如果缓存能够查询带,查询不到,取数据库中查,同步给redis
     */
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        List<ExamVO> examVOList;
        if (total == null || total <=0){
            //没数据,从数据库拿 并且同步
            //从哪个库查 还要通过竞赛id查询竞赛基本信息
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(examQueryDTO.getType(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else {
            //redis有数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            //total拿去方式不一样
            //因为可能redis异常,又重新刷新了
        }
        if (CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,total);
    }
}